package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-16
 * Time:19:18
 */
@Slf4j
@Controller
@RequestMapping("/user") // 可以省略
@ResponseBody
public class UserController {

    @Value("${img.path}")
    private String imgPath;

    @RequestMapping("/sayhi")
    public String sayHi() {
        return "你好，世界" + imgPath;
    }

    // 只支持设置的类型 此处设置为post
    @RequestMapping(method = RequestMethod.POST, value = "/sayhi2")
    public String sayHi2() {
        return "hello world";
    }

    // 只支持post类型的访问方式
    @PostMapping("/sayhi3")
    public String sayHi3() {
        return "你好，世界3";
    }

    @GetMapping("/sayhi4")
    public String sayHi4() {
        return "你好，世界4";
    }

    @RequestMapping("/getuserbyid")
    public UserInfo getUserById(Integer id) {
        // 不查数据库，伪代码，返回用户对象
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setUsername("张三");
        userInfo.setAge(18);
        return userInfo;
    }

    @RequestMapping("/login")
    public String login(String username, String password) {
        return username + ":" + password;
    }

    @RequestMapping("/login3")
    public HashMap<String, Object> login3(@RequestBody UserInfo userInfo) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        int state = 200;
        int data = -1; // 等于1，登录成功，否则登录失败
        String msg = "未知错误";
        if (StringUtils.hasLength(userInfo.getUsername()) && StringUtils.hasLength(userInfo.getPassword())) {
            if (userInfo.getUsername().equals("admin") && userInfo.getPassword().equals("admin")) {
                data = 1;
                msg = "";
            } else {
                msg = "用户名或密码失败！";
            }
        } else {
            msg = "非法参数";
        }
        result.put("state",state);
        result.put("data",data);
        result.put("msg",msg);
        return result;
    }

    @RequestMapping("/login2")
    public String login2(@RequestParam(value = "name", required = false) String username, String password) {
        return username + ":" + password;
    }

    @RequestMapping("/reg")
    public String reg(UserInfo userInfo) {
        return "用户信息：" + userInfo;
    }

    @RequestMapping("/reg2")
    public String reg2(@RequestBody UserInfo userInfo) {
        return "用户信息：" + userInfo;
    }

    @RequestMapping("/info/{id}/{username}")
    public String getUserInfo(@PathVariable Integer id, @PathVariable String username) {
        return "ID: " + id + " | name: " + username;
    }

    @PostMapping("upimg")
    public boolean upimg(Integer id, @RequestPart("img")MultipartFile file) {
        boolean result = false;
        // 1.目录
        // 2.图片名称（不能重复）使用UUID
        // 3.获取原上传图片的格式
        String fileName = file.getOriginalFilename();// 得到原图片名称
        fileName = fileName.substring(fileName.lastIndexOf("."));//得到图片后缀
        fileName = UUID.randomUUID().toString() + fileName;
        // 保存图片到本地目录
        try {
//            file.transferTo(new File("E:\\file\\img.png"));
            file.transferTo(new File(imgPath + fileName));

            result = true;
        } catch (IOException e) {
            log.error("上传图片失败：" + e.getMessage());
        }
        return result;
    }

    @RequestMapping("/setsess")
    public boolean setSession(HttpServletRequest request) {
        boolean result = false;
        // 1. 得到HttpSession
        HttpSession session = request.getSession(true);
        // 2. 使用setAtt设置值
        session.setAttribute("userinfo","userinfo");
        result = true;
        return result;
    }

}
